home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / setup.py < prev    next >
Encoding:
Python Source  |  2009-04-14  |  34.2 KB  |  893 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22.  
  23.  
  24. __version__ = '8.0'
  25. __title__ = 'Printer/Fax Setup Utility'
  26. __mod__ = 'hp-setup'
  27. __doc__ = "Installs HPLIP printers and faxes in the CUPS spooler. Tries to automatically determine the correct PPD file to use. Allows the printing of a testpage. Performs basic fax parameter setup."
  28.  
  29. # Std Lib
  30. import sys
  31. import getopt
  32. import time
  33. import os.path
  34. import re
  35. import os
  36. import gzip
  37.  
  38. try:
  39.     import readline
  40. except ImportError:
  41.     pass
  42.  
  43. # Local
  44. from base.g import *
  45. from base import device, utils, tui, models, module
  46. from prnt import cups
  47.  
  48. pm = None
  49.  
  50. def plugin_download_callback(c, s, t):
  51.     pm.update(int(100*c*s/t),
  52.              utils.format_bytes(c*s))
  53.  
  54.  
  55. nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
  56.  
  57. USAGE = [ (__doc__, "", "name", True),
  58.           ("Usage: %s [MODE] [OPTIONS] [SERIAL NO.|USB bus:device|IP|DEVNODE]" % __mod__, "", "summary", True),
  59.           utils.USAGE_MODE,
  60.           utils.USAGE_GUI_MODE,
  61.           utils.USAGE_INTERACTIVE_MODE,
  62.           utils.USAGE_SPACE,
  63.           utils.USAGE_OPTIONS,
  64.           ("Automatic mode:", "-a or --auto (-i mode only)", "option", False),
  65.           ("To specify the port on a multi-port JetDirect:", "--port=<port> (Valid values are 1\*, 2, and 3. \*default)", "option", False),
  66.           ("No testpage in automatic mode:", "-x (-i mode only)", "option", False),
  67.           ("To specify a CUPS printer queue name:", "-p<printer> or --printer=<printer> (-i mode only)", "option", False),
  68.           ("To specify a CUPS fax queue name:", "-f<fax> or --fax=<fax> (-i mode only)", "option", False),
  69.           ("Type of queue(s) to install:", "-t<typelist> or --type=<typelist>. <typelist>: print*, fax\* (\*default) (-i mode only)", "option", False),
  70.           ("To specify the device URI to install:", "-d<device> or --device=<device> (--qt4 mode only)", "option", False),
  71.           utils.USAGE_LANGUAGE,
  72.           utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  73.           utils.USAGE_HELP,
  74.           ("[SERIAL NO.|USB ID|IP|DEVNODE]", "", "heading", False),
  75.           ("USB bus:device (usb only):", """"xxx:yyy" where 'xxx' is the USB bus and 'yyy' is the USB device. (Note: The ':' and all leading zeros must be present.)""", 'option', False),
  76.           ("", "Use the 'lsusb' command to obtain this information.", "option", False),
  77.           ("IPs (network only):", 'IPv4 address "a.b.c.d" or "hostname"', "option", False),
  78.           ("DEVNODE (parallel only):", '"/dev/parportX", X=0,1,2,...', "option", False),
  79.           ("SERIAL NO. (usb and parallel only):", '"serial no."', "option", True),
  80.           utils.USAGE_EXAMPLES,
  81.           ("Setup using GUI mode:", "$ hp-setup", "example", False),
  82.           ("Setup using GUI mode, specifying usb:", "$ hp-setup -b usb", "example", False),
  83.           ("Setup using GUI mode, specifying an IP:", "$ hp-setup 192.168.0.101", "example", False),
  84.           ("One USB printer attached, automatic:", "$ hp-setup -i -a", "example", False),
  85.           ("USB, IDs specified:", "$ hp-setup -i 001:002", "example", False),
  86.           ("Network:", "$ hp-setup -i 66.35.250.209", "example", False),
  87.           ("Network, Jetdirect port 2:", "$ hp-setup -i --port=2 66.35.250.209", "example", False),
  88.           ("Parallel:", "$ hp-setup -i /dev/parport0", "example", False),
  89.           ("USB or parallel, using serial number:", "$ hp-setup -i US12345678A", "example", False),
  90.           ("USB, automatic:", "$ hp-setup -i --auto 001:002", "example", False),
  91.           ("Parallel, automatic, no testpage:", "$ hp-setup -i -a -x /dev/parport0", "example", False),
  92.           ("Parallel, choose device:", "$ hp-setup -i -b par", "example", False),
  93.           utils.USAGE_SPACE,
  94.           utils.USAGE_NOTES,
  95.           ("1. If no serial number, USB ID, IP, or device node is specified, the USB and parallel busses will be probed for devices.", "", 'note', False),
  96.           ("2. Using 'lsusb' to obtain USB IDs: (example)", "", 'note', False),
  97.           ("   $ lsusb", "", 'note', False),
  98.           ("         Bus 003 Device 011: ID 03f0:c202 Hewlett-Packard", "", 'note', False),
  99.           ("   $ hp-setup --auto 003:011", "", 'note', False),
  100.           ("   (Note: You may have to run 'lsusb' from /sbin or another location. Use '$ locate lsusb' to determine this.)", "", 'note', True),
  101.           ("3. Parameters -a, -f, -p, or -t are not valid in GUI (-u) mode.", "", 'note', True),
  102.           utils.USAGE_SPACE,
  103.           utils.USAGE_SEEALSO,
  104.           ("hp-makeuri", "", "seealso", False),
  105.           ("hp-probe", "", "seealso", False),
  106.         ]
  107.  
  108. def restart_cups():
  109.     if os.path.exists('/etc/init.d/cups'):
  110.         return '/etc/init.d/cups restart'
  111.  
  112.     elif os.path.exists('/etc/init.d/cupsys'):
  113.         return '/etc/init.d/cupsys restart'
  114.  
  115.     else:
  116.         return 'killall -HUP cupsd'
  117.  
  118.  
  119. mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
  120.                     (INTERACTIVE_MODE, GUI_MODE),
  121.                     (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4),
  122.                     run_as_root_ok=True)
  123.  
  124. opts, device_uri, printer_name, mode, ui_toolkit, loc = \
  125.     mod.parseStdOpts('axp:P:f:t:b:d:',
  126.                      ['ttl=', 'filter=', 'search=', 'find=',
  127.                       'method=', 'time-out=', 'timeout=',
  128.                       'printer=', 'fax=', 'type=', 'port=',
  129.                        'auto', 'device='],
  130.                       handle_device_printer=False)
  131.  
  132.  
  133. printer_name = None
  134. fax_name = None
  135. bus = None
  136. setup_print = True
  137. setup_fax = True
  138. makeuri = None
  139. auto = False
  140. testpage_in_auto_mode = True
  141. jd_port = 1
  142.  
  143. for o, a in opts:
  144.     if o == '-x':
  145.         testpage_in_auto_mode = False
  146.  
  147.     elif o in ('-P', '-p', '--printer'):
  148.         printer_name = a
  149.  
  150.     elif o in ('-f', '--fax'):
  151.         fax_name = a
  152.  
  153.     elif o in ('-d', '--device'):
  154.         device_uri = a
  155.  
  156.     elif o in ('-b', '--bus'):
  157.         bus = [x.lower().strip() for x in a.split(',')]
  158.         if not device.validateBusList(bus, False):
  159.             mod.usage(error_msg=['Invalid bus name'])
  160.  
  161.     elif o in ('-t', '--type'):
  162.         setup_fax, setup_print = False, False
  163.         a = a.strip().lower()
  164.         for aa in a.split(','):
  165.             if aa.strip() not in ('print', 'fax'):
  166.                 mod.usage(error_msg=['Invalid type.'])
  167.  
  168.             if aa.strip() == 'print':
  169.                 setup_print = True
  170.  
  171.             elif aa.strip() == 'fax':
  172.                 if not prop.fax_build:
  173.                     log.error("Cannot enable fax setup - HPLIP not built with fax enabled.")
  174.                 else:
  175.                     setup_fax = True
  176.  
  177.     elif o == '--port':
  178.         try:
  179.             jd_port = int(a)
  180.         except ValueError:
  181.             #log.error("Invalid port number. Must be between 1 and 3 inclusive.")
  182.             mod.usage(error_msg=['Invalid port number. Must be between 1 and 3 inclusive.'])
  183.  
  184.     elif o in ('-a', '--auto'):
  185.         auto = True
  186.  
  187.  
  188. try:
  189.     param = mod.args[0]
  190. except IndexError:
  191.     param = ''
  192.  
  193. log.debug("param=%s" % param)
  194.  
  195.  
  196. if mode == GUI_MODE:
  197.     if ui_toolkit == 'qt3':
  198.         if not utils.canEnterGUIMode():
  199.             log.error("%s requires GUI support (try running with --qt4). Also, try using interactive (-i) mode." % __mod__)
  200.             sys.exit(1)
  201.     else:
  202.         if not utils.canEnterGUIMode4():
  203.             log.error("%s requires GUI support (try running with --qt3). Also, try using interactive (-i) mode." % __mod__)
  204.             sys.exit(1)
  205.  
  206. if mode == GUI_MODE:
  207.     if ui_toolkit == 'qt3':
  208.         try:
  209.             from qt import *
  210.             from ui import setupform
  211.         except ImportError:
  212.             log.error("Unable to load Qt3 support. Is it installed?")
  213.             sys.exit(1)
  214.  
  215.         app = QApplication(sys.argv)
  216.         QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
  217.  
  218.         if loc is None:
  219.             loc = user_conf.get('ui', 'loc', 'system')
  220.             if loc.lower() == 'system':
  221.                 loc = str(QTextCodec.locale())
  222.                 log.debug("Using system locale: %s" % loc)
  223.  
  224.         if loc.lower() != 'c':
  225.             e = 'utf8'
  226.             try:
  227.                 l, x = loc.split('.')
  228.                 loc = '.'.join([l, e])
  229.             except ValueError:
  230.                 l = loc
  231.                 loc = '.'.join([loc, e])
  232.  
  233.             log.debug("Trying to load .qm file for %s locale." % loc)
  234.             trans = QTranslator(None)
  235.  
  236.             qm_file = 'hplip_%s.qm' % l
  237.             log.debug("Name of .qm file: %s" % qm_file)
  238.             loaded = trans.load(qm_file, prop.localization_dir)
  239.  
  240.             if loaded:
  241.                 app.installTranslator(trans)
  242.             else:
  243.                 loc = 'c'
  244.  
  245.         if loc == 'c':
  246.             log.debug("Using default 'C' locale")
  247.         else:
  248.             log.debug("Using locale: %s" % loc)
  249.             QLocale.setDefault(QLocale(loc))
  250.             prop.locale = loc
  251.             try:
  252.                 locale.setlocale(locale.LC_ALL, locale.normalize(loc))
  253.             except locale.Error:
  254.                 pass
  255.  
  256.         if not os.geteuid() == 0:
  257.             log.error("You must be root to run this utility.")
  258.  
  259.             QMessageBox.critical(None,
  260.                                  "HP Device Manager - Printer Setup Wizard",
  261.                                  "You must be root to run hp-setup.",
  262.                                   QMessageBox.Ok,
  263.                                   QMessageBox.NoButton,
  264.                                   QMessageBox.NoButton)
  265.  
  266.             sys.exit(1)
  267.  
  268.         try:
  269.             w = setupform.SetupForm(bus, param, jd_port)
  270.         except Error:
  271.             log.error("Unable to connect to HPLIP I/O. Please (re)start HPLIP and try again.")
  272.             sys.exit(1)
  273.  
  274.         app.setMainWidget(w)
  275.         w.show()
  276.  
  277.         app.exec_loop()
  278.  
  279.     else: # qt4
  280.         try:
  281.             from PyQt4.QtGui import QApplication, QMessageBox
  282.             from ui4.setupdialog import SetupDialog
  283.         except ImportError:
  284.             log.error("Unable to load Qt4 support. Is it installed?")
  285.             sys.exit(1)
  286.  
  287.         app = QApplication(sys.argv)
  288.  
  289.         if not os.geteuid() == 0:
  290.             log.error("You must be root to run this utility.")
  291.  
  292.             QMessageBox.critical(None,
  293.                                  "HP Device Manager - Printer Setup Wizard",
  294.                                  "You must be root to run hp-setup.",
  295.                                   QMessageBox.Ok,
  296.                                   QMessageBox.NoButton,
  297.                                   QMessageBox.NoButton)
  298.  
  299.             sys.exit(1)
  300.  
  301.  
  302.         dlg = SetupDialog(None, param, jd_port, device_uri)
  303.         dlg.show()
  304.         try:
  305.             log.debug("Starting GUI loop...")
  306.             app.exec_()
  307.         except KeyboardInterrupt:
  308.             sys.exit(0)
  309.  
  310.  
  311. else: # INTERACTIVE_MODE
  312.     try:
  313.         if not os.geteuid() == 0:
  314.             log.error("You must be root to run this utility.")
  315.             sys.exit(1)
  316.  
  317.         if not auto:
  318.             log.info("(Note: Defaults for each question are maked with a '*'. Press <enter> to accept the default.)")
  319.             log.info("")
  320.  
  321.         # ******************************* MAKEURI
  322.         if param:
  323.             device_uri, sane_uri, fax_uri = device.makeURI(param, jd_port)
  324.  
  325.         # ******************************* CONNECTION TYPE CHOOSER
  326.         if not device_uri and bus is None:
  327.             bus = tui.connection_table()
  328.  
  329.             if bus is None:
  330.                 sys.exit(0)
  331.  
  332.             log.info("\nUsing connection type: %s" % bus[0])
  333.  
  334.             log.info("")
  335.  
  336.         # ******************************* DEVICE CHOOSER
  337.  
  338.         if not device_uri:
  339.             device_uri = mod.getDeviceUri(device_uri, devices=device.probeDevices(bus))
  340.  
  341.         # ******************************* QUERY MODEL AND COLLECT PPDS
  342.         log.info(log.bold("\nSetting up device: %s\n" % device_uri))
  343.  
  344.         log.info("")
  345.         print_uri = device_uri.replace("hpfax:", "hp:")
  346.         fax_uri = device_uri.replace("hp:", "hpfax:")
  347.  
  348.         back_end, is_hp, bus, model, \
  349.             serial, dev_file, host, port = \
  350.             device.parseDeviceURI(device_uri)
  351.  
  352.         log.debug("Model=%s" % model)
  353.         mq = device.queryModelByURI(device_uri)
  354.  
  355.         if not mq or mq.get('support-type', SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
  356.             log.error("Unsupported printer model.")
  357.             sys.exit(1)
  358.  
  359.         if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED) and setup_fax:
  360.             #log.warning("Cannot setup fax - device does not have fax feature.")
  361.             setup_fax = False
  362.  
  363.         # ******************************* PLUGIN
  364.  
  365.         norm_model = models.normalizeModelName(model).lower()
  366.         plugin = mq.get('plugin', PLUGIN_NONE)
  367.  
  368.         plugin_installed = utils.to_bool(sys_state.get('plugin', 'installed', '0'))
  369.         if plugin > PLUGIN_NONE and not plugin_installed:
  370.             tui.header("PLUG-IN INSTALLATION")
  371.  
  372.             hp_plugin = utils.which('hp-plugin')
  373.  
  374.             if hp_plugin:
  375.                 if prop.gui_build:
  376.                     os.system("hp-plugin -i")
  377.                 else:
  378.                     os.system("hp-plugin")
  379.  
  380.         ppds = cups.getSystemPPDs()
  381.  
  382.         default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
  383.         stripped_model = cups.stripModel2(default_model)
  384.  
  385.         installed_print_devices = device.getSupportedCUPSDevices(['hp'])
  386.         for d in installed_print_devices.keys():
  387.             for p in installed_print_devices[d]:
  388.                 log.debug("found print queue '%s'" % p)
  389.  
  390.         installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
  391.         for d in installed_fax_devices.keys():
  392.             for f in installed_fax_devices[d]:
  393.                 log.debug("found fax queue '%s'" % f)
  394.  
  395.         # ******************************* PRINT QUEUE SETUP
  396.         if setup_print:
  397.  
  398.             tui.header("PRINT QUEUE SETUP")
  399.  
  400.             if not auto and print_uri in installed_print_devices:
  401.                 log.warning("One or more print queues already exist for this device: %s." %
  402.                     ', '.join(installed_print_devices[print_uri]))
  403.  
  404.                 ok, setup_print = tui.enter_yes_no("\nWould you like to install another print queue for this device", 'n')
  405.                 if not ok: sys.exit(0)
  406.  
  407.         if setup_print:
  408.             if auto:
  409.                 printer_name = default_model
  410.  
  411.             printer_default_model = default_model
  412.  
  413.             # Check for duplicate names
  414.             if device_uri in installed_print_devices and \
  415.                 printer_default_model in installed_print_devices[device_uri]:
  416.                     i = 2
  417.                     while True:
  418.                         t = printer_default_model + "_%d" % i
  419.                         if t not in installed_print_devices[device_uri]:
  420.                             printer_default_model += "_%d" % i
  421.                             break
  422.                         i += 1
  423.  
  424.             if not auto:
  425.                 if printer_name is None:
  426.                     while True:
  427.                         printer_name = raw_input(log.bold("\nPlease enter a name for this print queue (m=use model name:'%s'*, q=quit) ?" % printer_default_model))
  428.  
  429.                         if printer_name.lower().strip() == 'q':
  430.                             log.info("OK, done.")
  431.                             sys.exit(0)
  432.  
  433.                         if not printer_name or printer_name.lower().strip() == 'm':
  434.                             printer_name = printer_default_model
  435.  
  436.                         name_ok = True
  437.  
  438.                         for d in installed_print_devices.keys():
  439.                             for p in installed_print_devices[d]:
  440.                                 if printer_name == p:
  441.                                     log.error("A print queue with that name already exists. Please enter a different name.")
  442.                                     name_ok = False
  443.                                     break
  444.  
  445.                         for d in installed_fax_devices.keys():
  446.                             for f in installed_fax_devices[d]:
  447.                                 if printer_name == f:
  448.                                     log.error("A fax queue with that name already exists. Please enter a different name.")
  449.                                     name_ok = False
  450.                                     break
  451.  
  452.                         for c in printer_name:
  453.                             if c in (' ', '#', '/', '%'):
  454.                                 log.error("Invalid character '%s' in printer name. Please enter a name that does not contain this character." % c)
  455.                                 name_ok = False
  456.  
  457.                         if name_ok:
  458.                             break
  459.             else:
  460.                 printer_name = printer_default_model
  461.  
  462.             log.info("Using queue name: %s" % printer_name)
  463.  
  464.             default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
  465.             stripped_model = default_model.lower().replace('hp-', '').replace('hp_', '')
  466.  
  467.             log.info("Locating PPD file... Please wait.")
  468.             print_ppd = cups.getPPDFile2(stripped_model, ppds)
  469.             enter_ppd = False
  470.  
  471.             if print_ppd is None:
  472.                 enter_ppd = True
  473.                 log.error("Unable to find an appropriate PPD file.")
  474.  
  475.             else:
  476.                 print_ppd, desc = print_ppd
  477.                 log.info("\nFound PPD file: %s" % print_ppd)
  478.  
  479.                 if desc:
  480.                     log.info("Description: %s" % desc)
  481. #
  482.                     if not auto:
  483.                         log.info("\nNote: The model number may vary slightly from the actual model number on the device.")
  484.                         ok, ans = tui.enter_yes_no("\nDoes this PPD file appear to be the correct one")
  485.                         if not ok: sys.exit(0)
  486.                         if not ans: enter_ppd = True
  487.  
  488.  
  489.             if enter_ppd:
  490.                 enter_ppd = False
  491.  
  492.                 ok, enter_ppd = tui.enter_yes_no("\nWould you like to specify the path to the correct PPD file to use", 'n')
  493.                 if not ok: sys.exit(0)
  494.  
  495.                 if enter_ppd:
  496.                     ok = False
  497.  
  498.                     while True:
  499.                         user_input = raw_input(log.bold("\nPlease enter the full filesystem path to the PPD file to use (q=quit) :"))
  500.  
  501.                         if user_input.lower().strip() == 'q':
  502.                             log.info("OK, done.")
  503.                             sys.exit(0)
  504.  
  505.                         file_path = user_input
  506.  
  507.                         if os.path.exists(file_path) and os.path.isfile(file_path):
  508.  
  509.                             if file_path.endswith('.gz'):
  510.                                 nickname = gzip.GzipFile(file_path, 'r').read(4096)
  511.                             else:
  512.                                 nickname = file(file_path, 'r').read(4096)
  513.  
  514.                             try:
  515.                                 desc = nickname_pat.search(nickname).group(1)
  516.                             except AttributeError:
  517.                                 desc = ''
  518.  
  519.                             if desc:
  520.                                 log.info("Description for the file: %s" % desc)
  521.                             else:
  522.                                 log.error("No PPD 'NickName' found. This file may not be a valid PPD file.")
  523.  
  524.                             ok, ans = tui.enter_yes_no("\nUse this file")
  525.                             if not ok: sys.exit(0)
  526.                             if ans: print_ppd = file_path
  527.  
  528.                         else:
  529.                             log.error("File not found or not an appropriate (PPD) file.")
  530.  
  531.                         if ok:
  532.                             break
  533.                 else:
  534.                     log.error("PPD file required. Setup cannot continue. Exiting.")
  535.                     sys.exit(1)
  536.  
  537.             if auto:
  538.                 location, info = '', 'Automatically setup by HPLIP'
  539.             else:
  540.                 while True:
  541.                     location = raw_input(log.bold("Enter a location description for this printer (q=quit) ?"))
  542.  
  543.                     if location.strip().lower() == 'q':
  544.                         log.info("OK, done.")
  545.                         sys.exit(0)
  546.  
  547.                     # TODO: Validate chars
  548.                     break
  549.  
  550.                 while True:
  551.                     info = raw_input(log.bold("Enter additonal information or notes for this printer (q=quit) ?"))
  552.  
  553.                     if info.strip().lower() == 'q':
  554.                         log.info("OK, done.")
  555.                         sys.exit(0)
  556.  
  557.                     # TODO: Validate chars
  558.                     break
  559.  
  560.             log.info(log.bold("\nAdding print queue to CUPS:"))
  561.             log.info("Device URI: %s" % print_uri)
  562.             log.info("Queue name: %s" % printer_name)
  563.             log.info("PPD file: %s" % print_ppd)
  564.             log.info("Location: %s" % location)
  565.             log.info("Information: %s" % info)
  566.  
  567.             log.debug("Restarting CUPS...")
  568.             status, output = utils.run(restart_cups())
  569.             log.debug("Restart CUPS returned: exit=%d output=%s" % (status, output))
  570.  
  571.             if not os.path.exists(print_ppd): # assume foomatic: or some such
  572.                 status, status_str = cups.addPrinter(printer_name.encode('utf8'), print_uri,
  573.                     location, '', print_ppd, info)
  574.             else:
  575.                 status, status_str = cups.addPrinter(printer_name.encode('utf8'), print_uri,
  576.                     location, print_ppd, '', info)
  577.  
  578.             log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
  579.  
  580.             installed_print_devices = device.getSupportedCUPSDevices(['hp'])
  581.  
  582.             if print_uri not in installed_print_devices or \
  583.                 printer_name not in installed_print_devices[print_uri]:
  584.  
  585.                 log.error("Printer queue setup failed. Please restart CUPS and try again.")
  586.                 sys.exit(1)
  587.             else:
  588.                 pass
  589.                 # TODO:
  590.                 #service.sendEvent(hpssd_sock, EVENT_CUPS_QUEUES_CHANGED, device_uri=print_uri)
  591.  
  592.  
  593.         # ******************************* FAX QUEUE SETUP
  594.         if setup_fax and not prop.fax_build:
  595.             log.error("Cannot setup fax - HPLIP not built with fax enabled.")
  596.             setup_fax = False
  597.  
  598.         if setup_fax:
  599.  
  600.             try:
  601.                 from fax import fax
  602.             except ImportError:
  603.                 # This can fail on Python < 2.3 due to the datetime module
  604.                 setup_fax = False
  605.                 log.warning("Fax setup disabled - Python 2.3+ required.")
  606.  
  607.         log.info("")
  608.  
  609.         if setup_fax:
  610.  
  611.             tui.header("FAX QUEUE SETUP")
  612.  
  613.             if not auto and fax_uri in installed_fax_devices:
  614.                 log.warning("One or more fax queues already exist for this device: %s." % ', '.join(installed_fax_devices[fax_uri]))
  615.                 ok, setup_fax = tui.enter_yes_no("\nWould you like to install another fax queue for this device", 'n')
  616.                 if not ok: sys.exit(0)
  617.  
  618.         if setup_fax:
  619.             if auto: # or fax_name is None:
  620.                 fax_name = default_model + '_fax'
  621.  
  622.             fax_default_model = default_model + '_fax'
  623.  
  624.             # Check for duplicate names
  625.             if fax_uri in installed_fax_devices and \
  626.                 fax_default_model in installed_fax_devices[fax_uri]:
  627.                     i = 2
  628.                     while True:
  629.                         t = fax_default_model + "_%d" % i
  630.                         if t not in installed_fax_devices[fax_uri]:
  631.                             fax_default_model += "_%d" % i
  632.                             break
  633.                         i += 1
  634.  
  635.             if not auto:
  636.                 if fax_name is None:
  637.                     while True:
  638.                         fax_name = raw_input(log.bold("\nPlease enter a name for this fax queue (m=use model name:'%s'*, q=quit) ?" % fax_default_model))
  639.  
  640.                         if fax_name.lower().strip() == 'q':
  641.                             log.info("OK, done.")
  642.                             sys.exit(0)
  643.  
  644.                         if not fax_name or fax_name.lower().strip() == 'm':
  645.                             fax_name = fax_default_model
  646.  
  647.                         name_ok = True
  648.  
  649.                         for d in installed_print_devices.keys():
  650.                             for p in installed_print_devices[d]:
  651.                                 if fax_name == p:
  652.                                     log.error("A print queue with that name already exists. Please enter a different name.")
  653.                                     name_ok = False
  654.                                     break
  655.  
  656.                         for d in installed_fax_devices.keys():
  657.                             for f in installed_fax_devices[d]:
  658.                                 if fax_name == f:
  659.                                     log.error("A fax queue with that name already exists. Please enter a different name.")
  660.                                     name_ok = False
  661.                                     break
  662.  
  663.                         for c in fax_name:
  664.                             if c in (' ', '#', '/', '%'):
  665.                                 log.error("Invalid character '%s' in fax name. Please enter a name that does not contain this character." % c)
  666.                                 name_ok = False
  667.  
  668.                         if name_ok:
  669.                             break
  670.  
  671.             else:
  672.                 fax_name = fax_default_model
  673.  
  674.             log.info("Using queue name: %s" % fax_name)
  675.  
  676.             fax_type = mq.get('fax-type', FAX_TYPE_NONE)
  677.  
  678.             if fax_type == FAX_TYPE_SOAP:
  679.                 fax_ppd_name = 'HP-Fax2-hplip'
  680.             else:
  681.                 fax_ppd_name = 'HP-Fax-hplip'
  682.  
  683.             for f in ppds:
  684.                 if f.find(fax_ppd_name) >= 0:
  685.                     fax_ppd = f
  686.                     log.debug("Found PDD file: %s" % fax_ppd)
  687.                     break
  688.             else:
  689.                 log.error("Unable to find HP fax PPD file! Please check you HPLIP installation and try again.")
  690.                 sys.exit(1)
  691.  
  692.             if auto:
  693.                 location, info = '', 'Automatically setup by HPLIP'
  694.             else:
  695.                 while True:
  696.                     location = raw_input(log.bold("Enter a location description for this printer (q=quit) ?"))
  697.  
  698.                     if location.strip().lower() == 'q':
  699.                         log.info("OK, done.")
  700.                         sys.exit(0)
  701.  
  702.                     # TODO: Validate chars
  703.                     break
  704.  
  705.                 while True:
  706.                     info = raw_input(log.bold("Enter additonal information or notes for this printer (q=quit) ?"))
  707.  
  708.                     if info.strip().lower() == 'q':
  709.                         log.info("OK, done.")
  710.                         sys.exit(0)
  711.  
  712.                     # TODO: Validate chars
  713.                     break
  714.  
  715.             log.info(log.bold("\nAdding fax queue to CUPS:"))
  716.             log.info("Device URI: %s" % fax_uri)
  717.             log.info("Queue name: %s" % fax_name)
  718.             log.info("PPD file: %s" % fax_ppd)
  719.             log.info("Location: %s" % location)
  720.             log.info("Information: %s" % info)
  721.  
  722.             if not os.path.exists(fax_ppd): # assume foomatic: or some such
  723.                 status, status_str = cups.addPrinter(fax_name.encode('utf8'), fax_uri,
  724.                     location, '', fax_ppd, info)
  725.             else:
  726.                 status, status_str = cups.addPrinter(fax_name.encode('utf8'), fax_uri,
  727.                     location, fax_ppd, '', info)
  728.  
  729.             log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
  730.  
  731.             installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
  732.  
  733.             log.debug(installed_fax_devices)
  734.  
  735.             if fax_uri not in installed_fax_devices or \
  736.                 fax_name not in installed_fax_devices[fax_uri]:
  737.  
  738.                 log.error("Fax queue setup failed. Please restart CUPS and try again.")
  739.                 sys.exit(1)
  740.             else:
  741.                 pass
  742.                 # TODO:
  743.                 #service.sendEvent(hpssd_sock, EVENT_CUPS_QUEUES_CHANGED, device_uri=fax_uri)
  744.  
  745.  
  746.         # ******************************* FAX HEADER SETUP
  747.             tui.header("FAX HEADER SETUP")
  748.  
  749.             if auto:
  750.                 setup_fax = False
  751.             else:
  752.                 while True:
  753.                     user_input = raw_input(log.bold("\nWould you like to perform fax header setup (y=yes*, n=no, q=quit) ?")).strip().lower()
  754.  
  755.                     if user_input == 'q':
  756.                         log.info("OK, done.")
  757.                         sys.exit(0)
  758.  
  759.                     if not user_input:
  760.                         user_input = 'y'
  761.  
  762.                     setup_fax = (user_input == 'y')
  763.  
  764.                     if user_input in ('y', 'n', 'q'):
  765.                         break
  766.  
  767.                     log.error("Please enter 'y' or 'n'")
  768.  
  769.             if setup_fax:
  770.                 d = fax.getFaxDevice(fax_uri, disable_dbus=True)
  771.  
  772.                 try:
  773.                     d.open()
  774.                 except Error:
  775.                     log.error("Unable to communicate with the device. Please check the device and try again.")
  776.                 else:
  777.                     try:
  778.                         tries = 0
  779.                         ok = True
  780.  
  781.                         while True:
  782.                             tries += 1
  783.  
  784.                             try:
  785.                                 current_phone_num = str(d.getPhoneNum())
  786.                                 current_station_name = str(d.getStationName())
  787.                             except Error:
  788.                                 log.error("Could not communicate with device. Device may be busy. Please wait for retry...")
  789.                                 time.sleep(5)
  790.                                 ok = False
  791.  
  792.                                 if tries > 12:
  793.                                     break
  794.  
  795.                             else:
  796.                                 ok = True
  797.                                 break
  798.  
  799.                         if ok:
  800.                             while True:
  801.                                 if current_phone_num:
  802.                                     phone_num = raw_input(log.bold("\nEnter the fax phone number for this device (c=use current:'%s'*, q=quit) ?" % current_phone_num))
  803.                                 else:
  804.                                     phone_num = raw_input(log.bold("\nEnter the fax phone number for this device (q=quit) ?"))
  805.                                 if phone_num.strip().lower() == 'q':
  806.                                     log.info("OK, done.")
  807.                                     sys.exit(0)
  808.  
  809.                                 if current_phone_num and (not phone_num or phone_num.strip().lower() == 'c'):
  810.                                     phone_num = current_phone_num
  811.  
  812.                                 if len(phone_num) > 50:
  813.                                     log.error("Phone number length is too long (>50 characters). Please enter a shorter number.")
  814.                                     continue
  815.  
  816.                                 ok = True
  817.                                 for x in phone_num:
  818.                                     if x not in '0123456789-(+) ':
  819.                                         log.error("Invalid characters in phone number. Please only use 0-9, -, (, +, and )")
  820.                                         ok = False
  821.                                         break
  822.  
  823.                                 if not ok:
  824.                                     continue
  825.  
  826.                                 break
  827.  
  828.                             while True:
  829.                                 if current_station_name:
  830.                                     station_name = raw_input(log.bold("\nEnter the name and/or company for this device (c=use current:'%s'*, q=quit) ?" % current_station_name))
  831.                                 else:
  832.                                     station_name = raw_input(log.bold("\nEnter the name and/or company for this device (q=quit) ?"))
  833.                                 if station_name.strip().lower() == 'q':
  834.                                     log.info("OK, done.")
  835.                                     sys.exit(0)
  836.  
  837.                                 if current_station_name and (not station_name or station_name.strip().lower() == 'c'):
  838.                                     station_name = current_station_name
  839.  
  840.  
  841.                                 if len(station_name) > 50:
  842.                                     log.error("Name/company length is too long (>50 characters). Please enter a shorter name/company.")
  843.                                     continue
  844.                                 break
  845.  
  846.                             try:
  847.                                 d.setStationName(station_name)
  848.                                 d.setPhoneNum(phone_num)
  849.                             except Error:
  850.                                 log.error("Could not communicate with device. Device may be busy.")
  851.                             else:
  852.                                 log.info("\nParameters sent to device.")
  853.  
  854.                     finally:
  855.                         d.close()
  856.  
  857.         # ******************************* TEST PAGE
  858.         if setup_print:
  859.             print_test_page = False
  860.  
  861.             tui.header("PRINTER TEST PAGE")
  862.  
  863.             if auto:
  864.                 if testpage_in_auto_mode:
  865.                     print_test_page = True
  866.             else:
  867.                 ok, print_test_page = tui.enter_yes_no("\nWould you like to print a test page")
  868.                 if not ok: sys.exit(0)
  869.  
  870.             if print_test_page:
  871.                 path = utils.which('hp-testpage')
  872.  
  873.                 if printer_name:
  874.                     param = "-p%s" % printer_name
  875.                 else:
  876.                     param = "-d%s" % print_uri
  877.  
  878.                 if len(path) > 0:
  879.                     cmd = 'hp-testpage %s' % param
  880.                 else:
  881.                     cmd = 'python ./testpage.py %s' % param
  882.  
  883.                 log.debug(cmd)
  884.  
  885.                 os.system(cmd)
  886.  
  887.     except KeyboardInterrupt:
  888.         log.error("User exit")
  889.  
  890. log.info("")
  891. log.info("Done.")
  892.  
  893.